﻿using System;
using System.Collections.Generic;

namespace Kindohm.KSynth.Library
{
    public class CustomWaveForm : IWaveForm
    {
        WaveFormChunk currentChunk;
        int currentChunkIndex = 0;
        ushort maxPhaseAngle = ushort.MinValue;

        public List<WaveFormChunk> Chunks { get; set; }
        public string Name { get; set; }

        public CustomWaveForm()
        {
            this.Name = DateTime.Now.ToString();
            this.Chunks = new List<WaveFormChunk>();
        }

        public short GetSample(ushort phaseAngle)
        {
            if (phaseAngle > maxPhaseAngle)
                maxPhaseAngle = phaseAngle;

            if (this.currentChunk == null)
                this.currentChunk = this.Chunks[0];
            else if (phaseAngle < maxPhaseAngle)
            {
                this.currentChunk = this.Chunks[0];
            }

            if (this.currentChunk.EndPhase < phaseAngle)
            {
                this.currentChunkIndex++;
                if (this.currentChunkIndex >= this.Chunks.Count)
                {
                    this.currentChunkIndex = 0;
                    this.maxPhaseAngle = ushort.MinValue;
                }
                this.currentChunk = this.Chunks[this.currentChunkIndex];
            }

            return this.currentChunk.GetValue(phaseAngle);


        }
    }
}
